package com.slipper.system.backup.controller;

import com.slipper.constants.Constants;
import com.slipper.core.file.FileServiceUtil;
import com.slipper.core.file.vo.FileVO;
import com.slipper.system.affix.bo.AffixItemBO;
import com.slipper.system.affix.service.AffixItemService;
import com.slipper.system.backup.service.BackupRestoreService;
import com.slipper.util.*;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.slipper.system.backup.bo.BackupBO;
import com.slipper.system.backup.service.BackupService;

import java.io.File;
import java.util.Date;

/**
 * 数据备份信息表
 */
@RestController
@RequestMapping("/system/backup")
public class BackupController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private BackupService backupService;
    @Resource
    private BackupRestoreService backupRestoreService;
    @Resource
    private AffixItemService affixItemService;

    @PostMapping(value = "/queryPage")
    public String queryPage(@RequestBody BackupBO bo) {
        return ResultUtil.successResult(backupService.queryPage(bo));
    }

    @PostMapping(value = "/backup")
    public String backup(@RequestBody BackupBO bo) throws Exception {
        String fileName = "backup-" + DateUtil.format(new Date(), "yyyyMMddHHmmss");
        File file = File.createTempFile(fileName, ".dat");

        // 备份到文件
        backupRestoreService.backup(bo, file);

        FileVO fileVO = FileServiceUtil.saveFile(file);
        AffixItemBO affixItem = new AffixItemBO();
        affixItem.setSaveMode(fileVO.getMode());
        affixItem.setTrueName(bo.getName() + ".dat");
        affixItem.setSavePath(fileVO.getPath());
        affixItem.setFileSize(fileVO.getSize());
        affixItem.setCreateId(Constants.getCurrentUser().getEmployeeId());
        affixItem.setCreateTime(System.currentTimeMillis());
        affixItemService.save(affixItem);

        if (!file.delete()) {
            logger.error("临时文件【{}】删除失败！", file.getName());
        }

        bo.setFileId(affixItem.getId());
        if (backupService.save(bo) > 0) {
            return ResultUtil.successResult("备份成功！");
        } else {
            return ResultUtil.failureResult("备份失败！");
        }
    }

    @PostMapping(value = "/delete")
    public String delete(@RequestBody BackupBO bo) {
        return ResultUtil.deleteResult(backupService.delete(bo));
    }
}
